package com.maoke.mknews;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.maoke.mknews.adapter.NewsListViewAdapter;
import com.maoke.mknews.bean.News;

import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<News.ResultBean.DataBean> beanArrayList;
    private ListView newslistview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initView();
    }

    private void initData() {
        String url = "http://v.juhe.cn/toutiao/index?type=top&key=9f83c7459cbc081fd8b5bb41c5bd9303";
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        final Gson gson = new Gson();
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
                url,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
             //           Toast.makeText(MainActivity.this, "获取成功", Toast.LENGTH_SHORT).show();

                        News news = gson.fromJson(jsonObject.toString(),News.class);
                        beanArrayList = (ArrayList<News.ResultBean.DataBean>) news.getResult().getData();
                        newslistview.setAdapter(new NewsListViewAdapter(beanArrayList,getApplication()));

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(MainActivity.this, "获取失败", Toast.LENGTH_SHORT).show();
            }
        }
        );
        requestQueue.add(jsonObjectRequest);
    }

    private void initView() {

        newslistview = (ListView) findViewById(R.id.lv_news);

    }

}
